// ==UserScript==
// @name         知乎增强
// @namespace    https://gitee.com/linhq1999/OhMyScript
// @version      1.1
// @description  去除广告和快速折叠
// @downloadURL  https://gitee.com/linhq1999/OhMyScript/raw/master/dist/%E7%9F%A5%E4%B9%8E%E5%A2%9E%E5%BC%BA.user.js
// @updateURL    https://gitee.com/linhq1999/OhMyScript/raw/master/dist/%E7%9F%A5%E4%B9%8E%E5%A2%9E%E5%BC%BA.user.js
// @author       LinHQ
// @match        https://www.zhihu.com/*
// @grant        GM_setClipboard
// ==/UserScript==

'use strict';

let ads = document.getElementsByClassName("TopstoryItem--advertCard"),
    side_ads = document.getElementsByClassName("Pc-card Card"),
    btns = document.getElementsByTagName("button"),
    modal = document.getElementsByClassName('Button Modal-closeButton Button--plain');

function scan() {
    // 移除 “范围” 上的图片
    document.querySelector(".GlobalSideBar-category img")?.remove();

    // 移除侧边栏广告
    for (const sad of side_ads) {
        sad.remove();
    }

    // 移除主要广告
    for (const adv of ads) {
        adv.remove();
    }
}

(function () {
    document.body.addEventListener("keydown", e => {
        if (e.ctrlKey && e.key == 'c') {
            GM_setClipboard(window.getSelection()?.toString().trim() ?? "")
        }
        if (e.key == 'c' && e.altKey) {
            // 先检查弹出式评论
            if (modal.length != 0) {
                (<HTMLElement>modal[0]).click();
                return;
            }
            if (btns.length != 0) {
                for (const btn of btns) {
                    if (btn != null && btn.textContent?.includes("收起")) {
                        btn.click();
                    }
                }
            }
        }
        e.stopImmediatePropagation();
    })

    try {
        new MutationObserver((cl, ob) => {
            scan();
        }).observe(document.querySelector("#root") ?? document.body, { subtree: true, childList: true });
    } catch (error) {
        // 某些网站覆盖了 api，可以解决但我不想写了
        console.warn("Fallback to interval!");
        setInterval(scan, 1000);
    }
})()